package top.i51213.fastaction.png;

import java.io.IOException;
import java.io.OutputStream;

public class IDATWriter extends OutputStream {
    OutputStream out;
    byte[] buff;
    int max;
    int index;

    public IDATWriter(OutputStream out){
        this(out,0xffff);
    }
    public IDATWriter(OutputStream out, int max)
    {
        buff = new byte[max];
        this.max = max;
        index = 0;
        this.out = out;
    }

    private void writeIDAT() throws IOException {
        Chunk chunk = new Chunk();
        chunk.setLength(index);
        chunk.setType("IDAT");
        chunk.setData(buff);
        chunk.writeTo(out);
        index = 0;
    }

    @Override
    public void write(int b) throws IOException {
        this.write(new byte[]{(byte) b});
    }

    @Override
    public void write(byte[] b) throws IOException {
        this.write(b,0,b.length);
    }

    @Override
    public void write(byte[] buffer, int offset, int count) throws IOException {
        do
        {
            int canWrite = index + count <= max ? count : (max - index);
            System.arraycopy(buffer, offset, buff, index, canWrite);
            index = index + canWrite;
            offset += canWrite;
            count = count - canWrite;
            if (index == max)
            {
                writeIDAT();
            }
        } while (count > 0);
    }

    @Override
    public void close() throws IOException {
        if (index > 0)
            writeIDAT();
        out.flush();
    }

    @Override
    public void flush() throws IOException {
        out.flush();
    }
}
